﻿using System.Reflection;
using System.Xml.Linq;
using HomeRun.DB.Model;

namespace HomeRun.AspectCore.DataObserver
{
    public class DataObserver
    {
        private ScrumObject m_backupObj;


        public DataObserver(ScrumObject dataObj)
        {
            DataObj = dataObj;
            m_backupObj = (ScrumObject)dataObj.Clone();
        }

        public ScrumObject DataObj { get; set; }

        public XElement GenUpdateCmd()
        {
            XElement cmdElem = this.CreateCmdWithId("UPD");
            XElement assignmentsElem = this.CreateCmdAssignments();
            cmdElem.Add(assignmentsElem);
            return cmdElem;
        }

        public XElement GenDeleteCmd()
        {
            return this.CreateCmdWithId("DEL");
        }

        public XElement GenCreateCmd()
        {
            XElement cmdElem = this.CreateCmdWithId("UPD");
            XElement assignmentsElem = this.CreateCmdAssignments();
            cmdElem.Add(assignmentsElem);
            return cmdElem;
        }



        private XElement CreateCmdWithId(string op)
        {
            XElement cmdElem = new XElement("Command");
            XElement opElem = new XElement("Operation");
            opElem.SetAttributeValue("name", op);
            cmdElem.Add(opElem);
            XElement dtElem = new XElement("Datatable");
            dtElem.SetAttributeValue("name", "User");
            cmdElem.Add(dtElem);
            XElement conElem = new XElement("Conditions");
            cmdElem.Add(conElem);
            XElement condiElem = new XElement("Condition");
            condiElem.SetAttributeValue("name", "Id");
            condiElem.SetAttributeValue("value", DataObj.Id);
            condiElem.SetAttributeValue("valuetype", "Int");
            condiElem.SetAttributeValue("op", "Equal");
            conElem.Add(condiElem);

            return cmdElem;
        }

        private XElement CreateCmdAssignments()
        {
            XElement assElem = new XElement("Assignments");

            for (int i = 0; i < DataObj.GetType().GetProperties().Length; i++)
            {
                PropertyInfo[] devProperties = DataObj.GetType().GetProperties();
                PropertyInfo[] clonedevProperties = m_backupObj.GetType().GetProperties();

                if (devProperties[i].GetValue(DataObj, null).ToString() != clonedevProperties[i].GetValue(m_backupObj, null).ToString())
                {
                    XElement assigElem = new XElement("Assignment");
                    assigElem.SetAttributeValue("name", devProperties[i].Name);
                    assigElem.SetAttributeValue("value", devProperties[i].GetValue(DataObj, null));
                    assigElem.SetAttributeValue("valuetype", devProperties[i].PropertyType);
                    assElem.Add(assigElem);
                }
            }

            return assElem;
        }


    }
}
